package hncu.search.dao.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Set;

import org.springframework.stereotype.Repository;

import hncu.search.dao.UserDao;
import hncu.search.vo.User;

@Repository
public class UserImpl implements UserDao {

	private String path;
	
	private Set<User> hset ;
	
	{
		hset = new HashSet<User>();
	}
	
	private ObjectOutputStream out = null;
	private ObjectInputStream in = null;
	
	@Override
	public User getUserByName(String name) {
		if(hset.isEmpty()){
			return null;
		}
		for (User user : hset) {
			if(user.getName().equals(name)){
				return user;
			}
		}
		return null;
	}

	@Override
	public boolean updateUser(User user) {
		if(hset.isEmpty()){
			return false;
		}
		User temp = getUserByName(user.getName());
		if(temp==null){
			return false;
		}
		hset.remove(temp);
		hset.add(user);
		if(toWriteObject(path)){
			return true;
		}
		return false;
	}
	
	private boolean toWriteObject(String path){
		if(hset.isEmpty()){
			return false;
		}
		try{
			out = new ObjectOutputStream(
					new BufferedOutputStream(
					new FileOutputStream(path)));
					out.writeObject(hset);
					out.close();
					return true;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	private boolean toReaderObject(String path){
		if(!new File(path).exists()){
			try {
				new File(path).createNewFile();
//				addUser(new User("admin","admin",new Date()));
				addUser(new User());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try{
			in = new ObjectInputStream(
					new BufferedInputStream(
					new FileInputStream(path)));
					hset = (HashSet<User>) in.readObject();
					in.close();
					return true;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return false;
	}

	@Override
	public void initUserDao(String path) {
		this.path = path;
		if(!hset.isEmpty()){
			hset.clear();
		}
		toReaderObject(path);
//		System.out.println(hset.size());
	}

	@Override
	public boolean addUser(User user) {
		if(getUserByName(user.getName())!=null){
			return false;
		}
		hset.add(user);
		if(toWriteObject(path)){
			return true;
		}
		return false;
	}

	@Override
	public boolean deleteUser(String name, String password) {
		if(hset.isEmpty()){
			return false;
		}
		User user = getUserByName(name);
		if(user==null){
			return false;
		}
		if(!user.getPassword().equals(password)){
			return false;
		}
		hset.remove(user);
		if(toWriteObject(path)){
			return true;
		}
		return false;
	}
}
